import axios, { type Method } from 'axios'
import { getLocalToken, removeToken } from './auth'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000,
})

// 加上泛型
type Data<T> = {
  code: number
  message: string
  data: T
}
// 4. 请求工具函数
const request = <T>(url: string, method: Method = 'GET', submitData?: object) => {
  return service.request<T, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}
export { request }

service.interceptors.request.use(
  config => {
      const token = getLocalToken()
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
      return config
  },
  error => {
    ElMessage.error(error.response.data.msg)
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    ElMessage.error(error.response.data.msg)
    // Token 401处理
    if (error.response.status === 401) {
      // 1. 跳转到登录
      const router = useRouter()
      router.push('/login')
      // 2. 清空用户数据
      const store = useUserStore()
      removeToken()
    }
    return Promise.reject(error)
  },
)

export default service
